package com.test.controller;
import java.util.Date;

import com.test.entity.DemoEntity;
import com.test.entity.User;
import com.test.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("/user/{id}")
    User getUserById(@PathVariable Integer id){
        return userMapper.getById(id);
    }

    @GetMapping("/user/{username}/{nickname}")
    public String insertUser(@PathVariable("username") String username, @PathVariable("nickname") String nickname){
        User user = new User();
        user.setId(0);
        user.setUsername(username);
        user.setNickname(nickname);
        user.setBirthday(new Date());
        userMapper.insertUser(user);
        log.info("@@@" + new Date());
        return "success";
    }

    @GetMapping("/redis")
    public User redis(){
        User user= new User();
        user.setId(11);
        user.setUsername("aa");
        user.setNickname("xxx");
        user.setBirthday(new Date());
        ValueOperations<String, User> ops = redisTemplate.opsForValue();
        ops.set(String.valueOf(user.getId()), user);
        return ops.get(String.valueOf(user.getId()));
    }

    @GetMapping("/mongo")
    public DemoEntity getDemoEntity(){
        DemoEntity demoEntity = new DemoEntity();
        demoEntity.setId(2L);
        demoEntity.setTitle("hahaha");
        demoEntity.setDescription("一段描述");
        demoEntity.setBy("zhangsan");
        demoEntity.setUrl("http://www.baidu.com");
        mongoTemplate.save(demoEntity);

        Query query = new Query(Criteria.where("id").is(2L));
        DemoEntity entity = mongoTemplate.findOne(query, DemoEntity.class);
        return entity;
    }
}
